//
//  VideoDownLoadManager.m
//  News
//
//  Created by lanou3g on 15/11/10.
//  Copyright © 2015年 songhaowen. All rights reserved.
//

#import "VideoDownLoadManager.h"
#import "VideoModel.h"
#import "VideoDownLoadOperation.h"

@implementation VideoDownLoadManager

SingletonM(VideoDownLoadManager)


#pragma mark 开始下载
-(void)startAVideoWithVideoModel:(VideoModel *)downLoadVideo
{
    // 通知, 开始下载
    [[NSNotificationCenter defaultCenter] postNotificationName:k_newVideoDidStartDown object:downLoadVideo];
    
    if (!self.downLoadQueue) {
        self.downLoadQueue = [[NSOperationQueue alloc] init];
        self.downLoadQueue.maxConcurrentOperationCount = 3;
    }
    
    VideoDownLoadOperation *ope = [[VideoDownLoadOperation alloc] initWithDownloadVideoModel:downLoadVideo];
    
    // 从 VideoDownLoadOperation 实现 block 回调
    ope.updateBlock = ^(VideoModel *model){
        // 通过代理传给cell2进行数据展示和刷新
        if (self.delegate && [self.delegate respondsToSelector:@selector(videoDidUpdatedProgressWithVideoModel:)]) {
            [self.delegate videoDidUpdatedProgressWithVideoModel:model];
        }
    };
    ope.speedBlock = ^(CGFloat speed, VideoModel *model){
        if (self.delegate && [self.delegate respondsToSelector:@selector(videoDidUpdatedDownloadSpeedWithVideoModel:speed:)]) {
            [self.delegate videoDidUpdatedDownloadSpeedWithVideoModel:model speed:speed];
        }
    };
    
    // 方便管理, 查询是否有相同的url或者等等....
    [self.httpOperationDict setObject:ope forKey:downLoadVideo.mp4_url];
    
    // 任务加到队列中(VideoDownLoadOperation)自动下载
    [self.downLoadQueue addOperation:ope];
    
    // 数据源数组
    [self.downVideoArray addObject:downLoadVideo];
    
    
}

#pragma mark 暂停下载
-(void)downloadPausewithModel:(VideoModel *)pauseModel
{
    VideoDownLoadOperation *ope = [self.httpOperationDict objectForKey:pauseModel.mp4_url];
    
    [ope downloadPause];
}

#pragma mark 断点继续下载
-(void)downloadResumeWithModel:(VideoModel *)resumeModel
{
    VideoDownLoadOperation *ope = [self.httpOperationDict objectForKey:resumeModel.mp4_url];
    
    [ope downloadResume];
    
}

#pragma mark - 懒加载
- (NSMutableArray *)downVideoArray
{
    if (_downVideoArray == nil) {
        _downVideoArray = [NSMutableArray array];
    }
    return _downVideoArray;
}

- (NSMutableDictionary *)httpOperationDict
{
    if (_httpOperationDict == nil) {
        _httpOperationDict = [NSMutableDictionary dictionary];
    }
    return  _httpOperationDict;
}

@end
